<?php

namespace App\Admin\Repositories\Statistics;

use App\Helpers\KeyHandler;
use App\Models\Customer;
use App\Models\SalePerformance;
use Dcat\Admin\Repositories\Repository;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Dcat\Admin\Grid;
use Illuminate\Support\Facades\Cache;


class SaleRepository extends Repository
{

    /**
     * 排序字段
     * @var string
     */
    public mixed $order_column;

    /**
     * 排序方式
     * @var string
     */
    public mixed $order_type;


    public function get(Grid\Model $model): array
    {
        [$orderColumn, $orderType] = $model->getSort();
        $this->order_column = $orderColumn ?: 'date_time';
        $this->order_type = $orderType ?: 'desc';
        $date = $model->filter()->input('date', '');

        $is_month = request('type', 'day') === 'month';
        $date = $is_month ? ($date ? date('Y-m', strtotime($date . '-01')) : date('Y-m')) : ($date ? date('Y-m', strtotime($date)) : date('Y-m'));
        $days = $is_month ? getMonths($date) : getDays($date);
        rsort($days);
        return Cache::remember(sprintf(KeyHandler::SALE_STATISTICS, request('type', 'day'), $date), KeyHandler::SALE_STATISTICS_TTL, function () use ($days, $is_month) {
            $data = [];
            foreach ($days as $day) {
                $item_data['date'] = $day;
                //进线
                $item_data['enter'] = Customer::query()
                    ->when($is_month, function (Builder $builder) use ($day) {
                        list($year, $month) = explode('-', $day);
                        $builder->whereYear('sale_time', $year)->whereMonth('sale_time', $month);
                    }, function (Builder $builder) use ($day) {
                        $builder->whereDate('sale_time', $day);
                    })
                    ->count();
                //挂号
                $item_data['register'] = Customer::query()
                    ->whereNotNull('time_of_appointment')
                    ->when($is_month, function (Builder $builder) use ($day) {
                        list($year, $month) = explode('-', $day);
                        $builder->whereYear('time_of_appointment', $year)->whereMonth('time_of_appointment', $month);
                    }, function (Builder $builder) use ($day) {
                        $builder->whereDate('time_of_appointment', $day);
                    })
                    ->count();
                //看诊
                $item_data['consultation'] = Customer::query()
                    ->whereNotNull('consultation')
                    ->when($is_month, function (Builder $builder) use ($day) {
                        list($year, $month) = explode('-', $day);
                        $builder->whereYear('consultation', $year)->whereMonth('consultation', $month);
                    }, function (Builder $builder) use ($day) {
                        $builder->whereDate('consultation', $day);
                    })
                    ->count();
                //成交
                $item_data['deal'] = Customer::query()
                    ->whereNotNull('deal')
                    ->when($is_month, function (Builder $builder) use ($day) {
                        list($year, $month) = explode('-', $day);
                        $builder->whereYear('deal', $year)->whereMonth('deal', $month);
                    }, function (Builder $builder) use ($day) {
                        $builder->whereDate('deal', $day);
                    })
                    ->count();
                //成交业绩
                $item_data['money'] = SalePerformance::query()
                    ->when($is_month, function (Builder $builder) use ($day) {
                        list($year, $month) = explode('-', $day);
                        $builder->whereYear('created_at', $year)->whereMonth('created_at', $month);
                    }, function (Builder $builder) use ($day) {
                        $builder->whereDate('created_at', $day);
                    })
                    ->sum('money');
                self::getRate($item_data);
                $data[] = $item_data;
            }
            $data[] = self::getSum($data);
            return $data;
        });

    }

    public static function getRate(&$item_data)
    {
        //成交率(成交/挂号)
        $item_data['deal_rate'] = '0%';
        if ($item_data['deal'] && $item_data['register']) {
            $item_data['deal_rate'] = getPercentage($item_data['deal'], $item_data['register']) . '%';
        }
        //挂号率(挂号/进线)
        $item_data['register_rate'] = '0%';
        if ($item_data['register'] && $item_data['enter']) {
            $item_data['register_rate'] = getPercentage($item_data['register'], $item_data['enter']) . '%';
        }
        //看诊率(看诊/挂号)
        $item_data['consultation_rate'] = '0%';
        if ($item_data['consultation'] && $item_data['register']) {
            $item_data['consultation_rate'] = getPercentage($item_data['consultation'], $item_data['register']) . '%';
        }
        //客单(成交业绩/成交)
        $item_data['unit_price'] = '0%';
        if ($item_data['money'] && $item_data['deal']) {
            $item_data['unit_price'] = getDivide($item_data['money'], $item_data['deal']);
        }
    }


    public static function getSum($models): ?array
    {
        if (!empty($models)) {
            $item_data = ['date' => '总计'];
            $keys = array_keys(Arr::first($models));
            foreach ($keys as $key) {

                if (in_array($key, ['date', 'deal_rate', 'register_rate', 'consultation_rate', 'unit_price'])) {
                    continue;
                }
                $item_data[$key] = array_sum(array_column($models, $key));
            }
            self::getRate($item_data);
            return $item_data;
        }

        return null;
    }
}
